//pages/pay/SpellPay.js
var Zan = require('../../dist/index');
let WxNotificationCenter = require('../../utils/WxNotificationCenter.js');
var network = null;
var utils = null;
var api = null;
const app = getApp();

Page(Object.assign({}, Zan.TopTips, Zan.Toast, Zan.Switch, {

  /**
   * 页面的初始数据
   */
  data: {
    userName: null,
    deliverAddress: null,
    userPhone: null,
    products: [],
    content: "",
    allPrice: 0, // 总价
    orderId: null,
    orderNO: null,
    orderDesc: null,
    spellGroupId: null,
    mode1: 0,
    mode2: 1,
    radiochecked: 0,
    date: 0,
    dateStr: '自提时间',
    shop_details: {},
    day: [],
    multiIndex: [0, 0]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    // 注册列表刷新事件
    WxNotificationCenter.addNotification("RefreshNotification", this.refreshNotification, this)

    try {
      var value = wx.getStorageSync('RedeemDetailsData')
      if (value) {
        // Do something with return value
        this.setData({
          products: value,
          allPrice: value.currChangeIntegral
        })
        
      }
    } catch (e) {
      // Do something when catch error
    }


    /**
     * 获取个人及商家信息
     */
    if (app.globalData.userAndTenantInfo) {
      this.setData({
        distributorId: app.globalData.userAndTenantInfo.chiefUserId,
      })
    } else {
      app.userAndTenantInfoCallback = res => {
        this.setData({
          distributorId: res.chiefUserId,
        })
      }
    }

    let week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六', '周日', '周一'];
    let index = new Date().getDay();
    let day = [['今天（' + week[index] + '）', '明天（' + week[index + 1] + '）', '后天（' + week[index + 2] + '）'], ['上午', '下午', '晚上']];

    this.setData({
      day: day,
      date: new Date().getTime(),
      dateLink: 0,
      dateStr: day[0][0] + day[1][0]
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    WxNotificationCenter.removeNotification("RefreshNotification", this);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },

  bindMultiPickerChange: function (e) {
    this.setData({
      multiIndex: e.detail.value,
      date: new Date().getTime() + e.detail.value[0] * 24 * 60 * 60 * 1000,
      dateLink: e.detail.value[1],
      dateStr: this.data.day[0][e.detail.value[0]] + this.data.day[1][e.detail.value[1]]
    })
  },

  bindTextArea: function (e) {
    this.setData({
      content: e.detail.value
    })
  },

  /**
   * 选择地址
   */
  chooseAddress: function (e) {
    var that = this;
    wx.getSetting({
      success: function (res) {
        if (res) {
          if (!res.authSetting["scope.address"]) {
            wx.openSetting({
              success: function (res) {
                wx.chooseAddress({
                  success: function (res) {
                    that.setData({
                      userName: res.userName,
                      deliverAddress: res.provinceName + res.cityName + res.countyName + res.detailInfo,
                      userPhone: res.telNumber
                    })
                  }
                })
              }
            });
          } else {
            wx.chooseAddress({
              success: function (res) {
                that.setData({
                  userName: res.userName,
                  deliverAddress: res.provinceName + res.cityName + res.countyName + res.detailInfo,
                  userPhone: res.telNumber
                })
              }
            })
          }
        }
      }
    })
  },


  chooseStore: function (e) {
    wx.navigateTo({
      url: '/pages/myself/store/StoreInfo?gototype=1&mode=' + e.currentTarget.dataset.mode + '&pagepath=3&deliverytime=' + this.data.date
    })
  },


  /**
  * 选择支付方式
  */
  pay: function (e) {
    var data = {};
    data.linkType = 2;
    data.distributorId = this.data.distributorId;
    data.orderId = this.data.orderId; // 修改订单时有值
    if (this.data.products.product.ipType == 2){
      data.product = {
        id: this.data.products.product.id,
        count: this.data.products.count,
        price: this.data.products.selectedSpecRow.specValue2,
        specId: this.data.products.selectedSpecRow.id
      };
    }else{
      data.product = {
        id: this.data.products.product.id,
        count: this.data.products.count,
        price: this.data.products.product.changeIntegral,
        specId: null
      };
    }
    
    data.dateLink = this.data.dateLink;
    data.subscribeDate = utils.formatDate(new Date(this.data.date)) + ':00';
    data.content = this.data.content;

    /**
     * type: 0线上
     * type: 1线下
     */
    if (this.data.radiochecked == 1) {
      data.type = 1;
      data.customStoreId = this.data.shop_details.id; //门店id
      if (this.data.shop_details.name) {
        if (this.data.date != '自提时间') {
          if (this.data.allPrice > 0) {
            // 如果订单号存在，则为修改订单或再次购买，否则创建订单
            if (this.data.orderNO) {
              network._post_json(this, api.modifyOrder, data, modifySuccess);
            } else {
              network._post_json(this, api.createOrder, data, success);
            }
          } else {
            this.showZanTopTips('支付金额不能为0');
          }
        } else {
          this.showZanTopTips(this.prompt, '请选择自提日期');
        }

      } else {
        this.showZanTopTips(this.prompt, '请选择自提门店');
      }

    } else {
      if (this.data.deliverAddress) {
        data.userName = this.data.userName;
        data.deliverAddress = this.data.deliverAddress;
        data.userPhone = this.data.userPhone;
        data.type = 0;
        if (this.data.allPrice > 0) {
          // 如果订单号存在，则为修改订单或再次购买，否则创建订单
          if (this.data.orderNO) {
            network._post_json(this, api.modifyOrder, data, modifySuccess);
          } else {
            network._post_json(this, api.createOrder, data, success);
          }
        } else {
          this.showZanTopTips(this.prompt, '支付金额不能为0');
        }
      } else {
        this.showZanTopTips(this.prompt, '请选择地址');
      }
    }
  },
  radioChange: function (e) {
    var radiotxt = e.detail.value;
    if (radiotxt == "送货上门") {
      this.setData({
        mode1: 0,
        mode2: 1,
        radiochecked: 0
      })
    } else {
      this.setData({
        mode1: 1,
        mode2: 0,
        radiochecked: 1
      })
    }
  },
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },

  /**
   * 刷新地址
   */
  refreshNotification: function () {
    this.setData({
      shop_details: wx.getStorageSync('shop_details')
    })
  }

}))

// 生成订单
var success = function (that, res) {  
  
  that.showZanToast('积分兑换成功');

  setTimeout(function () {
    //获取页面栈
    var pages = getCurrentPages();
    if (pages.length > 1) {
      //上一个页面实例对象
      var prePage = pages[pages.length - 2];
      if (prePage.refresh && typeof (prePage.refresh) == "function") {
        prePage.refresh(that.data.products[0].count);
      }
    }
    wx.navigateBack();
  }, 1000);
}

// 修改订单
var modifySuccess = function (that, res) {
  if (res.data.message == '修改订单成功') {
    if (app.globalData.userAndTenantInfo) {
      // 购买
      network._post_json(that, api.wxPay, {
        shoppingCartIds: that.data.shoppingCartIds,
        products: that.data.products,
        appId: app.globalData.appId,
        orderId: res.data.data.orderNO,
        OrderDesc: res.data.data.orderDesc,
        totalFee: res.data.data.total
      }, wxPaySuccess);
    } else {
      app.userAndTenantInfoCallback = res => {
        // 购买
        network._post_json(that, api.wxPay, {
          shoppingCartIds: that.data.shoppingCartIds,
          products: that.data.products,
          appId: app.globalData.appId,
          orderId: res.data.orderNO,
          OrderDesc: res.data.orderDesc,
          totalFee: res.data.total
        }, wxPaySuccess);
      }
    }
  }
}

// 微信支付结果
var wxPaySuccess = function (that, res) {
  if (res.data.data) {
    wx.requestPayment({
      timeStamp: res.data.data.timeStamp,
      nonceStr: res.data.data.nonceStr,
      package: res.data.data.package,
      signType: res.data.data.signType,
      paySign: res.data.data.paySign,
      success: function (res) {
        //获取页面栈
        var pages = getCurrentPages();
        if (pages.length > 1) {
          //上一个页面实例对象
          var prePage = pages[pages.length - 2];
          if (prePage.refresh && typeof (prePage.refresh) == "function") {
            prePage.refresh(that.data.products[0].count);
          }
        }
        wx.navigateBack({

        })
      },
      fail: function (res) {

      },
    });
  }
}

var storeSuccess = function (that, res) {
  if (res.data.data) {

  }
}

var SpEndsuccess = function (that, res) {

}
